package com.dms.common.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.dms.common.config.AliyunSmsConfig;
import com.dms.common.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AliyunSmsUtils {

    @Autowired
    private Client smsClient;

    @Autowired
    private AliyunSmsConfig smsConfig;

    /**
     * 发送短信验证码
     * @param phone 手机号
     * @param code 验证码
     * @return 是否发送成功
     */
    public boolean sendSmsCode(String phone, String code) {
        try {
            SendSmsRequest request = new SendSmsRequest()
                    .setPhoneNumbers(phone)
                    .setSignName(smsConfig.getSignName())
                    .setTemplateCode(smsConfig.getTemplateCode())
                    .setTemplateParam("{\"code\":\"" + code + "\"}");

            SendSmsResponse response = smsClient.sendSms(request);
            
            if (!"OK".equals(response.getBody().getCode())) {
                throw new BusinessException("短信发送失败：" + response.getBody().getMessage());
            }
            
            return true;
        } catch (Exception e) {
            throw new BusinessException("短信发送异常：" + e.getMessage());
        }
    }
} 